package com.huluobo.kotlinim1907a.contract.add

import android.util.Log
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.BmobUser
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.FindListener
import com.huluobo.kotlinim1907a.data.AddFriendItem
import com.huluobo.kotlinim1907a.db.IMDatabase
import com.hyphenate.chat.EMClient
import org.jetbrains.anko.doAsync

/**
 * Created by lc on 2022/1/18.
 */
class AddFriendPresenter(val view: AddFriendContract.View) : AddFriendContract.Presenter {
    val addFriendItems = mutableListOf<AddFriendItem>()
    override fun search(key: String) {
        val query = BmobQuery<BmobUser>()
        query.addWhereContains("username", key)
            .addWhereNotEqualTo("username", EMClient.getInstance().currentUser)//搜索时排除掉当前登录用户

        //开始查询
        query.findObjects(object : FindListener<BmobUser>() {
            override fun done(list: MutableList<BmobUser>?, e: BmobException?) {
                if (e == null) {
                    val allContracts = IMDatabase.instance.getAllContacts()
                    doAsync {
                        list?.forEach {
                            //对比是否已经添加过好友
                            var isAdded = false
                            for (contact in allContracts) {
                                if (contact.name == it.username) {
                                    isAdded = true
                                }
                            }
                            val addFriendItem = AddFriendItem(it.username, it.createdAt, isAdded)
                            addFriendItems.add(addFriendItem)
                        }
                    }
                    runOnUIThread { view.onSearchSuccess() }
                    Log.i("TagA", "list:${list?.size}")
                } else runOnUIThread {
                    view.onSearchFailed()
                    Log.i("TagA", "onSearchFailed:${e.message}")
                }
            }
        })
    }
}